<div class="febs-container"  id="febs-menu">
    <div class="febs-body layui-fluid" lay-title="菜单管理">
        <div class="layui-row layui-col-space15 febs-full" style="margin: 0px -7.5px;">
            <div class="layui-col-md6 layui-col-sm6 layui-col-xs12 febs-full" style="padding: 0 7.5px;">
                <div class="layui-card febs-full">
                    <div class="layui-row" style="padding: 15px;">
                        <form class="layui-form layui-table-form" lay-filter="menu-table-form" id="menu-table-form">
                            <div class="jhg-body-search">
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm" style="width: auto !important;">菜单名称</label>
                                        <div class="layui-input-block" style="margin-left: 90px;">
                                            <input type="text" name="menuName" autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-btn layui-btn-primary table-action" id="query">
                                            <em class="layui-icon">&#xe848;</em>
                                        </div>
                                        <div class="layui-btn layui-btn-primary table-action" id="reset">
                                            <em class="layui-icon">&#xe79b;</em>
                                        </div>
                                        <div class="layui-btn layui-btn-primary table-action action-more"
                                             shiro:hasAnyPermissions="menu:add,menu:delete,menu:export">
                                            <em class="layui-icon">&#xe875;</em>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </form>
                        <div class="tree-container">
                            <div class="eleTree menuTree" lay-filter="menuTree" style="margin-left: 1rem"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6 layui-col-sm6 layui-col-xs12 febs-full" style="padding: 0 7.5px;">
                <div class="layui-card febs-full">
                    <div class="layui-card-header" id="form-header">新增菜单</div>
                    <div class="layui-row" style="padding: 15px;">
                        <form class="layui-form layui-table-form" action="" lay-filter="menu-form">
                            <div class="layui-form-item febs-hide">
                                <label class="layui-form-label febs-form-item-require">ID：</label>
                                <div class="layui-input-block">
                                    <input type="text" name="menuId" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item febs-hide">
                                <label class="layui-form-label">上级ID：</label>
                                <div class="layui-input-block">
                                    <input type="text" value="" name="parentId" readonly class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item febs-hide parentName">
                                <label class="layui-form-label febs-form-item-require">上级菜单：</label>
                                <div class="layui-input-block">
                                    <input type="text" value="" name="parentName" readonly class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label febs-form-item-require">菜单名称：</label>
                                <div class="layui-input-block">
                                    <input type="text" name="menuName" autocomplete="off" class="layui-input"
                                           minlength="2" maxlength="10" lay-verify="range" placeholder="请输入菜单名称">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label febs-form-item-require">菜单类型：</label>
                                <div class="layui-input-block">
                                    <input type="radio" name="type" lay-filter="menu-type" value="0" title="菜单"
                                           checked="">
                                    <input type="radio" name="type" lay-filter="menu-type" value="1" title="按钮">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">菜单图标：</label>
                                <div class="layui-input-block">
                                    <input type="text" name="icon" autocomplete="off" class="layui-input"
                                           maxlength="50" lay-verify="range" placeholder="请输入菜单图标">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">菜单URL：</label>
                                <div class="layui-input-block">
                                    <input type="text" name="url" autocomplete="off" class="layui-input"
                                           maxlength="50" lay-verify="range" placeholder="请输入菜单URL">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">菜单权限：</label>
                                <div class="layui-input-block">
                                    <input type="text" name="perms" autocomplete="off" class="layui-input"
                                           maxlength="50" lay-verify="range" placeholder="请输入菜单权限">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">菜单排序：</label>
                                <div class="layui-input-block">
                                    <input type="number" name="orderNum" autocomplete="off" class="layui-input"
                                           lay-verify="number" placeholder="请输入菜单排序">
                                </div>
                            </div>

                            <div class="layui-form-item febs-hide grantedSubsidiaryFlg">
                                <label class="layui-form-label" style="width: 90px;">授予子公司：</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" id="grantedSubsidiaryFlg-checkbox" name="grantedSubsidiaryFlg" lay-skin="switch" checked lay-text="授予|不授予"
                                           lay-filter="status">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">菜单状态：</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" id="status-checkbox" name="status" lay-skin="switch" checked lay-text="启用|禁用"
                                           lay-filter="status">
                                </div>
                            </div>
                            <div class="layui-form-item" style="text-align: center;">
                                <button type="reset" class="layui-btn febs-hide" id="reset-form"></button>
                                <button class="layui-btn" lay-submit="" lay-filter="menu-form-submit"
                                        id="submit-form">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script data-th-inline="none" type="text/javascript">
    layui.use(['dropdown', 'jquery', 'laydate', 'febs', 'form', 'commonJS', 'eleTree', 'validate'], function () {
        var $ = layui.jquery,
            febs = layui.febs,
            form = layui.form,
            validate = layui.validate,
            commonJS = layui.commonJS,
            eleTree = layui.eleTree,
            dropdown = layui.dropdown,
            $view = $('#febs-menu'),
            $query = $view.find('#query'),
            $reset = $view.find('#reset'),
            $searchForm = $view.find('#menu-table-form'),
            $menuName = $searchForm.find('input[name="menuName"]'),
            $type = $view.find('input[type="radio"][name="type"]'),
            $icon = $view.find('input[name="icon"]'),
            $icon_parent = $icon.parents('.layui-form-item'),
            $url = $view.find('input[name="url"]'),
            $url_parent = $url.parents('.layui-form-item'),
            $order = $view.find('input[name="orderNum"]'),
            $grantedSubsidiaryFlg = $view.find('#grantedSubsidiaryFlg-checkbox'),
            $status = $view.find('#status-checkbox'),
            $order_parent = $order.parents('.layui-form-item'),
            $header = $view.find('#form-header'),
            _currentMenuData,
            _selectNode,
            _menuTree,
            tableIns;

        form.verify(validate);
        form.render();

        var menuId = "";
        var parentId = "";
        var parentName = "";
        var menuName = "";
        var url = "";
        var perms = "";
        var icon = "";
        var menuType = "";
        var orderNum = "";
        var grantedSubsidiaryFlg = "0"

        dropdown.render({
            elem: $view.find('.action-more'),
            click: function (obj, elem, event) {
                if (obj.name === 'add') {
                    reset();
                    var selected = _menuTree.getChecked(false, true);
                    if (selected.length > 1) {
                        febs.alert.warn('只能选择一个节点作为父级！');
                        return false;
                    }
                    if (selected[0] && selected[0].type === '1') {
                        febs.alert.warn('不能选择按钮作为父级！');
                        return false;
                    }
                    let parentId = selected[0] ? selected[0].id : ''
                    let parentName = selected[0] ? selected[0].title : ''
                    form.val("menu-form", {
                        "parentId": parentId,
                        "parentName": parentName,
                        "grantedSubsidiaryFlg":false
                    });
                    form.render()
                    if(parentId && parentName){
                        $view.find(".parentName").show()
                    }else{
                        $view.find(".parentName").hide()
                    }
                    if( null == parentId || undefined === parentId || '' ==parentId){
                        $view.find(".grantedSubsidiaryFlg").show()
                    }else{
                        $view.find(".grantedSubsidiaryFlg").hide()
                    }

                }
                if (obj.name === 'delete') {
                    var checked = _menuTree.getChecked(false, true);
                    if (checked.length < 1) {
                        febs.alert.warn('请勾选需要删除的菜单或按钮');
                        return false;
                    }
                    var menuIds = [];
                    layui.each(checked, function (key, item) {
                        menuIds.push(item.id)
                    });
                    febs.modal.confirm('提示', '当您点击确定按钮后，这些记录将会被删除！', function () {
                        febs.get(ctx + 'menu/delete/' + menuIds, null, function () {
                            febs.alert.success('删除成功！');
                            reloadMenuTree();
                            reset();
                        })
                    });
                }
                if (obj.name === 'export') {
                    febs.download(ctx + 'menu/excel', {
                        "menuName": $menuName.val()?.trim()
                    }, '菜单信息表.xls');
                }
            },
            data: [
                {
                    name: 'add',
                    title: '新增',
                    perms: 'menu:add'
                }, {
                    name: 'delete',
                    title: '删除',
                    perms: 'menu:delete'
                }, {
                    name: 'export',
                    title: '导出Excel',
                    perms: 'menu:export'
                }
            ]
        });

        _menuTree = renderMenuTree();


        //拖拽回调
        eleTree.on('nodeDrag(menuTree)',function (data){

            let currentMenu = data.current.data.currentData.data
            let parentMenu = data.target.data.currentData.data
            if(currentMenu && parentMenu){
                currentMenu.parentId = parentMenu.menuId
                var type = currentMenu.type;
                menuId = currentMenu.menuId;
                parentId = currentMenu.parentId;
                parentName = parentMenu.title;
                menuName = currentMenu.menuName;
                url = currentMenu.url;
                perms = currentMenu.perms;
                icon = currentMenu.icon;
                menuType = currentMenu.type;
                orderNum = currentMenu.orderNum;
                grantedSubsidiaryFlg  = currentMenu.grantedSubsidiaryFlg;

                handleTypeChange(type);
                if (type === '0') { // 菜单
                    $header.text('修改菜单');
                } else { // 按钮
                    $header.text('修改按钮');
                }
                if(parentId != "0"){
                    $view.find(".parentName").show()
                }else{
                    $view.find(".parentName").hide()
                }
                form.val("menu-form", {
                    "icon": currentMenu.icon,
                    "url": currentMenu.url,
                    "orderNum": currentMenu.orderNum,
                    "type": currentMenu.type,
                    "menuName": currentMenu.menuName,
                    "perms": currentMenu.perms,
                    "parentId": currentMenu.parentId,
                    "parentName": parentMenu.menuName,
                    "menuId": currentMenu.menuId,
                    "grantedSubsidiaryFlg":false,
                    "status": currentMenu.status =='0' ? false : true
                });
            }
        })

        eleTree.on("nodeClick(menuTree)", function (d) {
            var data = d.data.currentData.data;
            var parentData = d.data.parentData.data;
            //console.log(data)
            _currentMenuData = data;
            var type = data.type;
            menuId = data.menuId;
            parentId = data.parentId;
            parentName = parentData.title;
            menuName = data.menuName;
            url = data.url;
            perms = data.perms;
            icon = data.icon;
            menuType = data.type;
            orderNum = data.orderNum;
            handleTypeChange(type);
            if (type === '0') { // 菜单
                $header.text('修改菜单');
            } else { // 按钮
                $header.text('修改按钮');
            }

            if(parentId != "0"){
                $view.find(".parentName").show()
            }else{
                $view.find(".parentName").hide()
            }
            form.val("menu-form", {
                "icon": data.icon,
                "url": data.url,
                "orderNum": data.orderNum,
                "type": data.type,
                "menuName": data.menuName,
                "perms": data.perms,
                "parentId": data.parentId,
                "parentName": parentData.title,
                "menuId": data.menuId,
                "grantedSubsidiaryFlg":"0" == data.grantedSubsidiaryFlg ? false :true,
                "status": data.status =='0' ? false : true
            });

            if( null == data.parentId || undefined === data.parentId || '' ==data.parentId || '0' ==data.parentId){
                $view.find(".grantedSubsidiaryFlg").show()
            }else{
                $view.find(".grantedSubsidiaryFlg").hide()
            }
        });

        form.on("radio(menu-type)", function (data) {
            handleTypeChange(data.value);
        });

        $reset.on('click', function () {
            $menuName.val('');
            reloadMenuTree();
            reset();
            menuId = "";
            parentId = "";
            menuName = "";
            url = "";
            perms = "";
            icon = "";
            menuType = "";
            orderNum = "";
        });

        $query.on('click', function () {
            //reloadMenuTree();
            _menuTree.search($menuName.val()?.trim());
            reset();
        });

        $icon.focus(function () {
            febs.modal.open('图标选择', 'others/febs/icon', {
                btn: ['确定'],
                yes: function () {
                    var icon = $('#febs-icon').find('.icon-active .icon-name').text();
                    if (icon) {
                        form.val("menu-form", {
                            "icon": 'layui-icon-' + icon
                        });
                    } else {
                        form.val("menu-form", {
                            "icon": ''
                        });
                    }
                    layer.closeAll();
                }
            });
        });

        function reset() {
            $view.find('#reset-form').trigger('click');
            handleTypeChange('0');
            $type.removeAttr("disabled");
        }

        function renderMenuTree(selKey) {
            _menuTree = eleTree.render({
                elem: '.menuTree',
                url: ctx + 'menu/tree',
                where: {
                    "menuName": $menuName.val()?.trim(),
                    "invalidate_ie_cache": new Date()
                },
                accordion: false,
                highlightCurrent: true,
                showCheckbox: true,
                checkStrictly: true,
                renderAfterExpand: false,
                expandOnClickNode: false,// 是否在点击节点的时候展开或者收缩节点， 默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。
                checkOnClickNode: false,
                spread: true,
                draggable:true,//是否开启拖拽功能
                searchNodeMethod: function (value, data) {
                    if (!value) return true;
                    return data.title.indexOf(value) !== -1;
                },
                request: {
                    name: "title",
                    key: "id",
                    children: "childs",
                    //checked: "checked",
                    data: "data"
                },
                response: {
                    statusName: "code",
                    statusCode: 200,
                    dataName: "data"
                },
                done: function (res) {
                    if (!!selKey) {
                        _menuTree.expandNode(selKey);
                    }
                }
            });
            //console.log(_menuTree)
            return _menuTree;
        }

        function reloadMenuTree(key) {
            _menuTree = renderMenuTree(key);
        }

        var handleTypeChange = function (type) {
            form.val("menu-form", {
                "icon": '',
                "url": '',
                "orderNum": ''
            });
            if (type === '1') {
                $header.text('新增按钮');
                $icon_parent.hide();
                $url_parent.hide();
                $order_parent.show();
            } else {
                $header.text('新增菜单');
                $icon_parent.show();
                $url_parent.show();
                $order_parent.show();
            }
        };

        form.on('submit(menu-form-submit)', function (data) {
            data.field.status = $status.is(':checked') ? '1' : '0';
            data.field.grantedSubsidiaryFlg = $grantedSubsidiaryFlg.is(':checked') ? '1' : '0';
            if(null == data.field.parentId || data.field.parentId==""){
                data.field.parentId="0"
            }
            if (data.field.menuId && $header.text().indexOf('修改') !== -1) {
                // if (febs.nativeEqual(data.field, _currentMenuData)) {
                //     febs.alert.warn('数据未作任何修改！');
                //     return false;
                // }
                febs.modal.confirm('保存提示', '是否更新菜单信息？', function () {
                    febs.post(ctx + 'menu/update', data.field, function () {
                        febs.alert.success('修改成功');
                        reloadMenuTree(data.field.parentId);
                        reset();
                    })
                });
            } else {
                febs.modal.confirm('保存提示', '是否保存菜单信息？', function () {
                    febs.post(ctx + 'menu', data.field, function () {
                        febs.alert.success('新增成功');
                        reloadMenuTree(data.field.parentId);
                        reset();
                    })
                });
            }
            return false;
        });
    });
</script>